package com.lxhdj.management.security;

import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Assert;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
    /**
     * 成功和失败hander
     */
    private final SecurityHandler securityHandler;

    private final UserDetailsServiceImpl userService;

    @Bean
    AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(userService);
        ProviderManager pm = new ProviderManager(daoAuthenticationProvider);
        return pm;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // login放行，其他请求验证
        CustomAuthorizationManager customAuthorizationManager = new CustomAuthorizationManager();
        http.authorizeHttpRequests(authorize->authorize.requestMatchers("/login").permitAll().anyRequest().access(customAuthorizationManager));
        http.exceptionHandling(exception -> exception.accessDeniedHandler(securityHandler).authenticationEntryPoint(securityHandler) );
        // 请求参数用username和password
//        http.formLogin(form->{
//            form.successHandler(securityHandler);
//            form.failureHandler(securityHandler);
//        });
        http.formLogin(form->form.disable());
        http.csrf(csrf->csrf.disable());
        // 自定义登录处理添加认证提供者
//        UserDetailsServiceImpl userDetailService = http.getSharedObject(ApplicationContext.class).getBean(UserDetailsServiceImpl.class);
//        Assert.notNull(userDetailService,"UserDetailsService 不能为空");
//        PasswordEncoder passwordEncoder = http.getSharedObject(ApplicationContext.class).getBean(PasswordEncoder.class);
        http.authenticationProvider(new CustomAuthenticationProvider(userService, passwordEncoder()));
        AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userService);
        AuthenticationManager authenticationManager = authenticationManagerBuilder.build();
        http.authenticationManager(authenticationManager);
        CustomAuthenticationFilter customAuthenticationFilter =new CustomAuthenticationFilter();
        customAuthenticationFilter.setAuthenticationManager(authenticationManager);
        customAuthenticationFilter.setAuthenticationSuccessHandler(securityHandler);
        customAuthenticationFilter.setAuthenticationFailureHandler(securityHandler);
        http.addFilterAt(customAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        // 自定义权限，处理登录人信息
        http.addFilterAfter(new CustomAuthorizationFilter(securityHandler), UsernamePasswordAuthenticationFilter.class);

        return http.build();

    }
}
